package com.efounder.tbs;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.PopupMenu;

import com.efounder.common.BaseRequestManager;
import com.efounder.common.TCommonRequestManager;
import com.efounder.frame.baseui.EFActivity;
import com.efounder.mobilemanager.R;
import com.efounder.view.CommonTitleBar;
import com.qmuiteam.qmui.widget.QMUILoadingView;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.utilcode.util.FileIntentUtils;
import com.utilcode.util.FileUtils;
import com.utilcode.util.LogUtils;
import com.utilcode.util.StringUtils;
import com.utilcode.util.ToastUtils;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Tbs文件预览
 *
 * @author yqs
 */
public class FileDisplayActivity extends EFActivity {


    private String TAG = "FileDisplayActivity";
    private SuperFileView2 mSuperFileView;
    //本地文件路径或者文件url都可以
    private String filePath;
    private QMUILoadingView qmuiLoadingview;
    private ImageView mRightImageView;
    private TextView mTitleBarText;
    private String mFileName;


    /**
     * 预览文件
     * 预览文件
     *
     * @param context
     * @param localFilePath 文件路径
     */
    public static void show(Context context, String localFilePath) {
        show(context, localFilePath, null);
    }

    /**
     * 预览文件
     *
     * @param context
     * @param filePathOrUrl 文件路径或者url
     * @param fileName
     */
    public static void show(Context context, String filePathOrUrl, String fileName) {
        show(context, filePathOrUrl, fileName, true);
    }

    /**
     * 预览文件
     *
     * @param context
     * @param filePathOrUrl 文件路径或者url
     * @param fileName
     */
    public static void show(Context context, String filePathOrUrl, String fileName, boolean showTitle) {
        //创建缓存目录
        String dirPath = getCacheDirString();
        FileUtils.createOrExistsDir(dirPath);

        Intent intent = new Intent(context, FileDisplayActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("path", filePathOrUrl);
        bundle.putBoolean("showTitle", showTitle);
        if (!TextUtils.isEmpty(fileName)) {
            bundle.putSerializable("fileName", fileName);
        }
        intent.putExtras(bundle);
        context.startActivity(intent);

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_display);
        this.hideEFTitleView();

        initTitle();

        init();
    }

    private void initTitle() {
        CommonTitleBar titleBar = (CommonTitleBar) findViewById(R.id.titleBar);
        boolean showTitle = getIntent().getBooleanExtra("showTitle", true);
        if (!showTitle) {
            titleBar.setVisibility(View.GONE);
            return;
        }
        titleBar.getLeftImageView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleBar.setRightImageResource(R.drawable.ef_right_menu);
        titleBar.getRightImageView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopMenu(v);
            }
        });
        mRightImageView = titleBar.getRightImageView();
        mRightImageView.setVisibility(View.GONE);
        try {
            ViewGroup.LayoutParams layoutParams = mRightImageView.getLayoutParams();
            layoutParams.height = -1;
            mRightImageView.setLayoutParams(layoutParams);
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }

        mTitleBarText = titleBar.getCenterTextView();
        mTitleBarText.setEllipsize(TextUtils.TruncateAt.MIDDLE);
        mFileName = (String) getIntent().getSerializableExtra("fileName");
        if (!TextUtils.isEmpty(mFileName)) {
            mTitleBarText.setText(mFileName);
            titleBar.getCenterTextView().setEllipsize(TextUtils.TruncateAt.MIDDLE);
        } else {
            mTitleBarText.setText("文件预览");
        }
    }

    public void showPopMenu(View view) {
        PopupMenu menu = new PopupMenu(this, view);
        menu.getMenuInflater().inflate(R.menu.tbs_menu_file, menu.getMenu());
        menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.three_app) {
                    FileIntentUtils.openFileByPath(FileDisplayActivity.this, filePath);
                }
                return true;
            }
        });
        menu.setOnDismissListener(new PopupMenu.OnDismissListener() {
            @Override
            public void onDismiss(PopupMenu menu) {
            }
        });
        try {
            Class<?> classPopupMenu = Class.forName(menu.getClass().getName());
            Field mPopup = classPopupMenu.getDeclaredField("mPopup");
            mPopup.setAccessible(true);
            Object menuPopupHelper = mPopup.get(menu);
            Class<?> classPopupHelper = Class.forName(menuPopupHelper.getClass().getName());
            Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class);
            setForceIcons.invoke(menuPopupHelper, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        menu.show();
    }

    public void init() {
        mSuperFileView = (SuperFileView2) findViewById(R.id.mSuperFileView);
        qmuiLoadingview = (QMUILoadingView) findViewById(R.id.qmui_loadingview);
        qmuiLoadingview.setVisibility(View.GONE);
        mSuperFileView.setOnGetFilePathListener(new SuperFileView2.OnGetFilePathListener() {
            @Override
            public void onGetFilePath(SuperFileView2 mSuperFileView2) {
                getFilePathAndShowFile(mSuperFileView2);
            }

            @Override
            public void onNotSupportFileType() {
                //不支持的文件格式
                new QMUIDialog.MessageDialogBuilder(FileDisplayActivity.this).setTitle(R.string.common_text_hint)
                        .setMessage("不支持的文件格式").addAction(R.string.common_text_cancel, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                }).addAction("其它应用打开", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        FileIntentUtils.openFileByPath(FileDisplayActivity.this, filePath);
                    }
                }).show();
            }
        });

        String path = (String) getIntent().getSerializableExtra("path");
        if (!TextUtils.isEmpty(path)) {
            Log.i(TAG, "要打开的文件路径为:" + path);
            this.filePath = path;
            mSuperFileView.show();
        } else {
            ToastUtils.showLong("预览失败，文件不存在");
        }
    }


    /**
     * 调用mSuperFileView.show();后会回调该方法
     *
     * @param mSuperFileView2
     */
    private void getFilePathAndShowFile(SuperFileView2 mSuperFileView2) {


        if (filePath.startsWith("http")) {//网络地址要先下载
            downLoadFromNet(filePath, mSuperFileView2);

        } else {
            mRightImageView.setVisibility(View.VISIBLE);
            try {
                mSuperFileView2.displayFile(new File(filePath));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "FileDisplayActivity-->onDestroy");
        if (mSuperFileView != null) {
            mSuperFileView.onStopDisplay();
        }
        TCommonRequestManager.getInstance().cannelOkHttpRequest(TAG);
    }


    private void downLoadFromNet(final String url, final SuperFileView2 mSuperFileView2) {

        //1.获取下载的文件
//        File cacheFile = getCacheFile(url);
//        if (cacheFile.exists()) {
//            mSuperFileView2.displayFile(cacheFile);
//        } else {
//            //2.已下载的缓存文件不存在，下载文件
//
//        }
        qmuiLoadingview.setVisibility(View.VISIBLE);

        TCommonRequestManager.getInstance().downLoadFileNew(TAG, url, getIntent().getStringExtra("fileName"), getCacheDirString(), new BaseRequestManager.ReqProgressCallBack<File>() {
            @Override
            public void onProgress(long total, long current) {

            }

            @Override
            public void onReqSuccess(File file) {
                mRightImageView.setVisibility(View.VISIBLE);
                if (StringUtils.isEmpty(mFileName)) {
                    mTitleBarText.setText(file.getName());
                }
                filePath = file.getAbsolutePath();
                try {
                    mSuperFileView2.displayFile(file);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                qmuiLoadingview.setVisibility(View.GONE);

            }

            @Override
            public void onReqFailed(String errorMsg) {
                qmuiLoadingview.setVisibility(View.GONE);
                new QMUIDialog.MessageDialogBuilder(FileDisplayActivity.this).setMessage("文件下载失败").addAction(R.string.common_text_cancel, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                }).show();

            }
        });
    }

    /***
     * 获取缓存目录
     *
     * @return
     */
    public static String getCacheDirString() {
        return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "TbsReaderTemp";

    }
}
